﻿#region using
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using dotNET.Utility;
using dotNET.Utility.Security;
using dotNET.Data;
using dotNET.Repository;
using dotNET.Domain.Entities;
using dotNET.Application.Infrastructure;
using dotNET.Dto;
using System.Threading;
#endregion

namespace dotNET.Application.App
{
    public class UserApp : App, IUserApp
    {
        public IRepositoryBase<User> _userRep { get; set; }
        public IRepositoryBase<Role> _roleRep { get; set; }
        public IRepositoryBase<LoginLog> _loginLogRep { get; set; }
        public IRepositoryBase<Department> _DepartmentRep { get; set; }
        public IOperateLogApp _operateLogApp { get; set; }

        #region 修改登录状态
        /// <summary>
        /// 修改登录状态
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="agentId"></param>
        /// <param name="curUser"></param>
        /// <returns></returns>
        public async Task test()
        {
            Thread.Sleep(3000);
          //  NLogger.Info("test11:" + context.guid);
            int aa=  await   _userRep.testExecuteAsync("insert into agentgen_0(Name)values('"+DateTime.Now.ToString()+"')");
            Thread.Sleep(3000);
          //  NLogger.Info("test22:" + context.guid);
            int aa1 = await _userRep.testExecuteAsync("insert into agentgen_0(Name)values('" + DateTime.Now.ToString() + "')");
            Thread.Sleep(3000);
         //   NLogger.Info("test33:" + context.guid);
            int aa2 = await _userRep.testExecuteAsync("insert into agentgen_0(Name)values('" + DateTime.Now.ToString() + "')");
            Thread.Sleep(3000);
            NLogger.Info("test44:"+aa);

        }


        #endregion

        #region 修改登录状态
        /// <summary>
        /// 修改登录状态
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="agentId"></param>
        /// <param name="curUser"></param>
        /// <returns></returns>
        public async Task<R> updatestatus(long Id, CurrentUser curUser)
        {
           var   entry=  await GetAsync(Id);
            if(entry==null)
                return R.Err(msg:"该用户不存在");
            int s = 1;
           if( entry.State==1)
            {
                s = 0;
            }
            var r = await _userRep.UpdateAsync<User>(new { Id = Id, State = s });
            if (r)
            {
                string logstr = "用户的登录状态从" + (entry.State == 1 ? "启用到禁用" : "禁用到启用");
                return R.Suc();
            }
            else
            {
                return R.Err(msg: "修改失败");
            }       
        }


        #endregion

        #region 用户退出操作
        /// <summary>
        /// 用户退出操作
        /// </summary>
        /// <param name="curUser">登录用户信息</param>
        /// <returns></returns>
        public async Task LogOffAsync(CurrentUser curUser)
        {
            await _operateLogApp.CustomLogAsync(curUser, "用户退出", curUser.RealName + "进行了退出操作");
        } 
        #endregion



        /// <summary>
        ///  根据账号模糊查询获取列表
        /// </summary>
        /// <param name="q"></param>
        /// <returns></returns>
        public async Task<List<IdAccountDto>> SelectDataAsync(string q)
        {
            if (string.IsNullOrWhiteSpace(q))
                return new List<IdAccountDto>();

            var result = await _userRep.GetListAsync<IdAccountDto>("where Account like @Account", new { Account = "%" + q.Trim() + "%" });
            if (result == null || result.Count() == 0)
            {
                return new List<IdAccountDto>();
            }

            return result.ToList();
        }



        public async Task<PageResult<UserSunpleDto>> GetPageAsync(int pageNumber, int rowsPrePage, UserOption filter)
        {
            List<UserSunpleDto> data = new List<UserSunpleDto>();
            PageResult<UserSunpleDto> list = new PageResult<UserSunpleDto>();
          //  string conditions = "";
            string orderby = " id desc";
            //Dictionary<string, dynamic> param = new Dictionary<string, dynamic>();

            //if (!string.IsNullOrWhiteSpace(filter.Name))
            //{
            //    param.Add("name", "%" + filter.Name.Trim() + "%");
            //    conditions += " where  `name` like @name  ";
            //}

            var sql = Sql.Builder;
            sql = sql.Where("`DeleteMark` is NULL");
            if (filter.AgentId.HasValue)
            {
                sql = sql.Where("`AgentId`=@AgentId", new { AgentId = filter.AgentId });
            }
            if (!string.IsNullOrWhiteSpace(filter.Account))
            {
                sql = sql.Where("`Account`=@Account", new { Account = filter.Account });
            }
            if (!string.IsNullOrWhiteSpace(filter.RealName))
            {
                sql = sql.Where("`RealName`=@RealName", new { RealName = filter.RealName });
            }



            var tlist = await _userRep.GetListPagedAsync(pageNumber, rowsPrePage, sql.SQL, orderby, sql.Arguments);


            data = MapperHelper.MapList<User, UserSunpleDto>(tlist.ToList());
             
            List<long> roleIds = tlist.Select(o => o.RoleId).Distinct().ToList();
            if (roleIds.Count() > 0)
            {
                var roles = await _roleRep.GetListAsync("Where `Id` in (" + string.Join(",", roleIds) + ")");
                foreach (var d in data)
                {
                    var r = roles.FirstOrDefault(o => o.Id == d.RoleId);
                    d.RoleName = r?.Name;
                }
            }


            List<long?> DepartmentIds = tlist.Select(o => o.DepartmentId).Distinct().ToList();
            DepartmentIds.Remove(null);
            if (DepartmentIds.Count() > 0)
            {
               
                var Departments = await _DepartmentRep.GetListAsync("Where `Id` in (" + string.Join(",", DepartmentIds) + ")");
                foreach (var d in data)
                {
                    var r = Departments.FirstOrDefault(o => o.Id == d.DepartmentId);
                    d.deptname = r?.Name;
                }
            }


            list.Data = data.ToList();
            int total = await _userRep.RecordCountAsync(sql.SQL, sql.Arguments);
            list.ItemCount = total;
            return list;
            
        }




        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="pageParam"></param>
        /// <param name="conditions"></param>
        /// <returns></returns>
        public async Task<Page<UserSunpleDto>> PagerAsync(UserOption option)
        {
            //var sql = Sql.Builder;
            //sql = sql.Where("`DeleteMark` is NULL");
            //if (option.AgentId.HasValue)
            //{
            //    sql = sql.Where("`AgentId`=@AgentId", new { AgentId = option.AgentId });
            //}
            //if (!string.IsNullOrWhiteSpace(option.Account))
            //{
            //    sql = sql.Where("`Account`=@Account", new { Account = option.Account });
            //}
            //if (!string.IsNullOrWhiteSpace(option.RealName))
            //{
            //    sql = sql.Where("`RealName`=@RealName", new { RealName = option.RealName });
            //}

            //List<UserSunpleDto> data = new List<UserSunpleDto>();
            //int total = await _userRep.RecordCountAsync(sql.SQL, sql.Arguments);
            //if (total > 0)
            //{
            //    if (option.Offset > total)
            //        option.Offset = total;

            //    List<User> users = (await _userRep.GetListPagedAsync<User>(option.PageIndex, option.Limit, sql.SQL, option.OrderBy, sql.Arguments)).ToList();
            //    data = MapperHelper.MapList<User, UserSunpleDto>(users);
            //    List<long> roleIds = users.Select(o => o.RoleId).Distinct().ToList();
            //    if (roleIds.Count() > 0)
            //    {
            //        var roles = await _roleRep.GetListAsync("Where `Id` in (" + string.Join(",", roleIds) + ")");
            //        foreach (var d in data)
            //        {
            //            var r = roles.FirstOrDefault(o => o.Id == d.RoleId);
            //            d.RoleName = r?.Name;
            //        }
            //    }
            //}
            //return new Page<UserSunpleDto>(total, data);
            return null;
        }

        /// <summary>
        /// 添加管理人员
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<R> InsertAsync(User entity, CurrentUser curUser)
        {
            entity.Id = entity.CreateId();
            entity.UserSecretkey = "";
            entity.CreatorTime = DateTime.Now;
            entity.CreatorUserId = curUser.Id;
            var r = await InsertAsync(entity);
            if (!string.IsNullOrEmpty(r.Error))
            {
                return R.Err(msg: r.Error);
            }
            await _operateLogApp.InsertLogAsync<User>(curUser, "添加用户", entity);
            return R.Suc();
        }

        /// <summary>
        /// 添加（判断Account是否已存在）
        /// </summary>
        /// <param name="entity"></param>
        /// <returns>-1： 失败 ， 0：已存在 ，1：成功</returns>
        public  async Task<(string Error, User user)> InsertAsync(User entity)
        {
            //已存在
            int count = await _userRep.RecordCountAsync("where `Account`=@Account", new { Account = entity.Account });
            if (count > 0)
            {
                return ("帐号已存在", null);
            }
            int r = await _userRep.InsertAsync(entity);
            if (r != 1)
            {
                return ($"数据更新失败", null);
            }
            return (string.Empty, null);
        }


        /// <summary>
        ///  更新用户信息
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="curUser"></param>
        /// <returns></returns>
        public async Task<R> UpdateUserInfoAsync(User entity, CurrentUser curUser)
        {
            bool status = await _userRep.UpdateAsync<User>(entity);
            if (!status)
            {
                return R.Err(msg:  "数据更新失败");
            }
            return R.Suc();
        }

        /// <summary>
        /// 删除管理人员
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<R> DeleteAsync(long Id, long agentId, CurrentUser curUser)
        {
            var r = await DeleteAsync(Id, agentId, curUser.Id);
            if (!string.IsNullOrEmpty(r.Error))
            {
                return R.Err(msg:r.Error);
            }
            return R.Suc();
        }

        /// <summary>
        /// 删除（假删除）
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="agentId"></param>
        /// <param name="optId"></param>
        /// <returns>-1： 失败 ， 0：不存在 ，1：成功</returns>
        public async Task<(string Error, User User)> DeleteAsync(long Id, long agentId, long optId)
        {
            User user = await _userRep.GetAsync(Id);
            if (user == null || user.DeleteMark == true)
            {
                return ("帐号不存在", null);
            }
            user.DeleteMark = true;
            user.DeleteTime = DateTime.Now;
            user.DeleteUserId = optId;
            bool b = await _userRep. UpdateAsync(user);
            if (!b)
            {
                return ($"数据更新失败", null);
            }
            return (string.Empty, user);
        }


        /// <summary>
        /// 代理登录
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public async Task<(string Error, User User)> AgentLoginAsync(string account, string password, string ip = "")
        {
            User user = await _userRep.QueryFirstOrDefaultAsync<User>("Where `Account`=@Account", new { Account = account });
            if (user == null )
            {
                return ($"帐号不存在", null);
            }
            if (user.State ==0)
            {
                return ($"帐号禁止登录", null);
            }
            if (user.Password != password)
            {
                return ($"密码不正确", null);
            }
            LoginLog loginlog = new LoginLog
            {  
                LoginId = user.Id,
                LoginType = "Agent",
                IP = ip,
                CreatorTime = DateTime.Now
            };
            loginlog.Id = loginlog.CreateId();
            await _loginLogRep.InsertAsync(loginlog);
            return (string.Empty, user);
        }

        /// <summary>
        /// Saas后台管理登录
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public async Task<(string Error, User User)> SaasLoginAsync(string account, string password, string ip = "")
        {
            User user = await _userRep.QueryFirstOrDefaultAsync<User>("where `Account`=@Account", new { Account = account });
            if (user == null )
            {
                return ($"帐号不存在", null);
            }
            if (user.State == 0)
            {
                return ($"帐号禁止登录", null);
            }
            if (user.Password != password)
            {
                return ($"密码不正确", null);
            }
            CurrentUser curUser = new CurrentUser
            {             
                Id = user.Id,
                RealName = user.Account,
                LoginIPAddress = ip
              
            };
            await   _operateLogApp.CustomLogAsync(curUser, "用户登录", user.RealName+"进行了登录操作");
             await _userRep.UpdateAsync<User>(new { Id = user.Id, LastLoginTime = DateTime.Now });
            return (string.Empty, user);
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="password">旧密码</param>
        /// <param name="newPassword">新密码</param>
        /// <returns></returns>
        public async Task<R> ChangePasswordAsync(long Id, string password, string newPassword, long agentId, CurrentUser curUser)
        {
            User user = await _userRep.GetAsync(Id);
            if (user == null || user.DeleteMark == true)
            {
                return R.Err("1001", $"帐号({Id})不存在");
            }
            if (user.Password != MD5Encrypt.MD5(password))
            {
                return R.Err("1003", $"原密码不正确");
            }
            int r = await _userRep.ExecuteAsync("update `users` set `Password`=@newPassword  where Id=@Id", new { Id = Id, DeleteMark = true, newPassword = MD5Encrypt.MD5(newPassword) });
            if (r != 1)
            {
                return R.Err("2001", "数据更新失败");
            }
            return R.Suc();
        }

        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="newPassword"></param>
        /// <param name="agentId"></param>
        /// <returns></returns>
        public async Task<R> ResetPasswordAsync(long Id, string password, long agentId, CurrentUser curUser)
        {
            User user = await _userRep.GetAsync(Id);
            if (user == null)
            {
                return R.Err("1001", $"帐号({Id})不存在");
            }
            int r = await _userRep.ExecuteAsync("update `users` set `Password`=@Password  where Id=@Id", new { Id = Id, Password = MD5Encrypt.MD5(password) });
            if (r != 1)
            {
                return R.Err("2001", "数据更新失败");
            }
            return R.Suc();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<User> GetAsync(long Id)
        {
            return await _userRep.GetAsync(Id);
        }

    }
}